import React, { useEffect, useState, useRef } from 'react';
import { View, Text, StyleSheet, SafeAreaView, TouchableOpacity, ScrollView, Image, Animated } from 'react-native';
import Header from '../../../../components/Header';

interface DeviceDetailProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

// 全局变量用于传递设备数据
declare global {
    var deviceDetailData: any;
}

interface CollapsibleSectionProps {
    title: string;
    isExpanded: boolean;
    onToggle: () => void;
    children: React.ReactNode;
    iconSource: any;
}

const CollapsibleSection: React.FC<CollapsibleSectionProps> = ({ title, isExpanded, onToggle, children, iconSource }) => {
    const animatedHeight = useRef(new Animated.Value(0)).current;
    const animatedOpacity = useRef(new Animated.Value(0)).current;
    const arrowRotation = useRef(new Animated.Value(0)).current;

    useEffect(() => {
        if (isExpanded) {
            // 展开动画
            Animated.parallel([
                Animated.timing(animatedHeight, {
                    toValue: 1,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(animatedOpacity, {
                    toValue: 1,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(arrowRotation, {
                    toValue: 1,
                    duration: 500,
                    useNativeDriver: true,
                }),
            ]).start();
        } else {
            // 收起动画
            Animated.parallel([
                Animated.timing(animatedHeight, {
                    toValue: 0,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(animatedOpacity, {
                    toValue: 0,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(arrowRotation, {
                    toValue: 0,
                    duration: 500,
                    useNativeDriver: true,
                }),
            ]).start();
        }
    }, [isExpanded]);

    return (
        <View style={styles.section}>
            <TouchableOpacity style={styles.sectionHeader} onPress={onToggle}>
                <View style={styles.headerLeft}>
                    <Image source={iconSource} style={styles.sectionIcon} />
                    <Text style={styles.sectionTitle}>{title}</Text>
                    <Text style={styles.asterisk}>*</Text>
                </View>
                <Animated.Image
                    source={require('../../../../assets/xiala.png')}
                    style={[
                        styles.arrowIcon,
                        {
                            transform: [{
                                rotate: arrowRotation.interpolate({
                                    inputRange: [0, 1],
                                    outputRange: ['0deg', '180deg']
                                })
                            }]
                        }
                    ]}
                />
            </TouchableOpacity>
            <Animated.View
                style={[
                    styles.sectionContent,
                    {
                        maxHeight: animatedHeight.interpolate({
                            inputRange: [0, 1],
                            outputRange: [0, 500], // 根据内容调整最大高度
                        }),
                        opacity: animatedOpacity,
                        margin: 0,
                        // padding: 0,
                        paddingTop: 0,
                        paddingBottom: 0,

                    }
                ]}
            >
                {children}
            </Animated.View>
        </View>
    );
};

const DeviceDetail: React.FC<DeviceDetailProps> = ({ onNavigateToLogin, onBackPress }) => {
    const [deviceData, setDeviceData] = useState<any>(null);
    const [expandedSections, setExpandedSections] = useState({
        basic: true,
        maintenance: false,
        operation: false,
        asset: false,
        location: false,
    });

    useEffect(() => {
        // 获取全局传递的设备数据
        if (global.deviceDetailData) {
            setDeviceData(global.deviceDetailData);
            // console.log('DeviceDetail页面接收到的设备数据:', global.deviceDetailData);
        }
    }, []);

    const toggleSection = (section: keyof typeof expandedSections) => {
        setExpandedSections(prev => {
            // 如果当前section已经展开，则收起它
            if (prev[section]) {
                return {
                    ...prev,
                    [section]: false
                };
            }
            // 如果当前section未展开，则先收起所有section，再展开当前section
            const newState = {
                basic: false,
                maintenance: false,
                operation: false,
                asset: false,
                location: false,
            };
            return {
                ...newState,
                [section]: true
            };
        });
    };

    const renderField = (label: string, value: string) => (
        <View style={styles.fieldRow}>
            <Text style={styles.fieldLabel}>{label}</Text>
            <Text style={styles.fieldValue}>{value}</Text>
        </View>
    );

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="设备详情"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />
            <ScrollView style={styles.content}>
                <CollapsibleSection
                    title="设备基本信息"
                    isExpanded={expandedSections.basic}
                    onToggle={() => toggleSection('basic')}
                    iconSource={require('../../../../assets/shebeixinxi/shebeijibenxinxi.png')}
                >
                    {renderField('设备名称', deviceData?.device_name || '未知')}
                    {renderField('设备编号', deviceData?.device_num || '未知')}
                    {renderField('资产编号', deviceData?.fixed_assets_num || '未知')}
                    {renderField('序列号', deviceData?.sn || '未知')}
                    {renderField('型号', deviceData?.model || '未知')}
                    {renderField('设备类型', deviceData?.device_type_kk || '未知')}
                    {renderField('生产厂商', deviceData?.vendor_name || '未知')}
                </CollapsibleSection>

                <CollapsibleSection
                    title="维保信息"
                    isExpanded={expandedSections.maintenance}
                    onToggle={() => toggleSection('maintenance')}
                    iconSource={require('../../../../assets/shebeixinxi/weibaoxinxi.png')}
                >
                    {renderField('维保公司', deviceData?.defend_name || '未知')}
                    {renderField('生产日期', deviceData?.produce_date || '未知')}
                    {renderField('购买日期', deviceData?.buy_date || '未知')}
                    {renderField('使用寿命', deviceData?.life || '未知')}
                    {renderField('使用寿命类型', deviceData?.life_type || '未知')}
                    {renderField('设备管理员', deviceData?.device_admin_name || '未知')}
                </CollapsibleSection>

                <CollapsibleSection
                    title="运行信息"
                    isExpanded={expandedSections.operation}
                    onToggle={() => toggleSection('operation')}
                    iconSource={require('../../../../assets/shebeixinxi/yunxingxinxi.png')}
                >
                    {renderField('ip地址', deviceData?.ip || '未知')}
                    {renderField('加工一小时费用(元)', deviceData?.cost ? `${deviceData.cost}元` : '未知')}
                    {renderField('当前使用时长(小时)', deviceData?.used_time || '0小时')}
                    {renderField('连续工作时长预警值(小时)', deviceData?.warning_time ? `${deviceData.warning_time}小时` : '未知')}
                    {renderField('是否参加排程', deviceData?.schedule ? '是' : '否')}
                </CollapsibleSection>

                <CollapsibleSection
                    title="资产信息"
                    isExpanded={expandedSections.asset}
                    onToggle={() => toggleSection('asset')}
                    iconSource={require('../../../../assets/shebeixinxi/zichanxinxi.png')}
                >
                    {renderField('资产原值(元)', deviceData?.original_cost ? `${deviceData.original_cost}元` : '未知')}
                    {renderField('资产净值(元)', deviceData?.now_cost ? `${deviceData.now_cost}元` : '未知')}
                </CollapsibleSection>

                <CollapsibleSection
                    title="位置信息"
                    isExpanded={expandedSections.location}
                    onToggle={() => toggleSection('location')}
                    iconSource={require('../../../../assets/shebeixinxi/weizhixinxi.png')}
                >
                    {renderField('车间', deviceData?.room_name || '未知')}
                    {renderField('资源组', deviceData?.group_num || '未知')}
                    {renderField('所属工位', deviceData?.station_name || '未知')}
                </CollapsibleSection>
            </ScrollView>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    content: {
        flex: 1,
        padding: 0,

    },
    section: {
        backgroundColor: '#f5f5f5',
        marginBottom: 0,
    },
    sectionHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 16,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    headerLeft: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    sectionIcon: {
        width: 20,
        height: 20,
        marginRight: 8,
    },
    sectionTitle: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
    },
    asterisk: {
        color: '#ff4444',
        fontSize: 16,
        marginLeft: 4,
    },
    arrowIcon: {
        width: 16,
        height: 16,
    },

    sectionContent: {
        padding: 16,
        backgroundColor: '#fff',
    },
    fieldRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    fieldLabel: {
        fontSize: 14,
        color: '#666',
        flex: 1,
    },
    fieldValue: {
        fontSize: 14,
        color: '#333',
        flex: 1,
        textAlign: 'right',
    },
});

export default DeviceDetail; 